import sys
import network
import json
from .microWebSrv import MicroWebSrv
from .fs_services import list_dir, upload_file, rm_file, resources_info
from .configs import configs, UDP_DISCOVERY_PORT
from .webpage import ROUTES_WEBPAGE
from .states import bootstrap_states
try:
    from .udp_broadcast import broadcast_udp_msg

    from esp_toytrain import ALL_FUNCTIONAL_ROUTES
except Exception as e:
    print("error occurred when trying to import functions:", e)
    ALL_FUNCTIONAL_ROUTES = []
try:
    from shared_types import *
except ImportError:
    pass
import network
import utime



def create_ap(ssid, password):
    ap = network.WLAN(network.AP_IF)       # 配置为AP模式
    ap.active(True)                        # 激活AP模式
    ap.config(essid=ssid, password=password)  # 设置热点SSID和密码
    ap.ifconfig(("192.168.213.1", '255.255.255.0', "192.168.213.1", '8.8.8.8'))
    bootstrap_states.ip = "192.168.213.1"
    print("Wifi service started, the server ip is:", ap.ifconfig()[0])


def create_sta(ssid, password: str):
    if ssid.strip() == "":
        print("ssid invalid")
        return False
    sta_if = network.WLAN(network.STA_IF)  # 配置wifi模式为station
    if not sta_if.isconnected():   # 判断有无连接
        print('connecting to network...')
        sta_if.active(True)        # 激活wifi接口
        sta_if.config(pm=sta_if.PM_NONE)  # 关闭节能模式以降低时延
        sta_if.connect(ssid, password)  # 连接现有wifi网络，需要替换为已知的热点名称和密码
        waiting_seconds = 10
        while not sta_if.isconnected():
            utime.sleep(1)   # 未连接上就等待一下，直到连接成功
            waiting_seconds -= 1
            if waiting_seconds <= 0:   # 超时退出
                sta_if.active(False)
                print("Connect failed, now starting AP mode...")
                return False
    ip, mask, _, _ = sta_if.ifconfig()
    print('network config:', ip)  # 输出当前wifi网络给自己分配的网络参数
    bootstrap_states.ip = ip
    bootstrap_states.mask = mask
    try:
        data: "ConnectedMsg" = {"type": "ETT_JOIN", "ip": ip, "mask": mask,
                                "name": configs.config['name'], 'role': configs.config['role']}
        broadcast_udp_msg(ip, UDP_DISCOVERY_PORT, mask,
                          json.dumps(data).encode('ascii'))
    except Exception as e:
        sys.print_exception(e)
        print("Broadcast message failed..")
    return True


def create_wifi_service():
    if not create_sta(configs.config['ssid'], configs.config["password"]):
        create_ap("ESP-Toy-Train", "12345678")


mws = None


def start_http_server():
    global mws
    mws = MicroWebSrv(
        routeHandlers=[
            ("/fs/listdir", "GET", list_dir),
            ("/fs/upload", "POST", upload_file),
            ("/fs/remove", "POST", rm_file),
            ("/sys/resources_info", "GET", resources_info),
        ]+ROUTES_WEBPAGE+ALL_FUNCTIONAL_ROUTES
    )      # TCP port 80 and files in /flash/www
    mws.Start(threaded=True)  # Starts server in a new thread
    print("Threaded http server started...")
